﻿using System;
using System.Web.UI.WebControls;
using Alserve.Ffl;
using Alserve.Ffl.Data;

public partial class ffl_admin_ImportMatches : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (!Security.IsAdmin(Page))
                Response.Redirect("~//ffl//anonymous//default.aspx");

            GetCompetitions();
            PopulateMonthDropDown();
        }
    }

    private void RefreshMatchList()
    {
        EspnImport espn = new EspnImport();
        MatchRepeater.DataSource = espn.GetNewMatchesByCompetitionAndDate(Convert.ToInt32(CompetitionDropDown.SelectedValue), Convert.ToDateTime(MonthDropDown.SelectedValue));
        MatchRepeater.DataBind();
    }

    private void GetCompetitions()
    {
        Competition thisCompetition = new Competition();
        if (thisCompetition.LoadAll())
        {
            CompetitionDropDown.DataSource = thisCompetition.DefaultView;
            CompetitionDropDown.DataValueField = Competition.ColumnNames.Id;
            CompetitionDropDown.DataTextField = Competition.ColumnNames.CompetitionName;
            CompetitionDropDown.DataBind();
        }
    }

    private void PopulateMonthDropDown()
    {
        //Get previous August
        DateTime startDate = DateTime.Today;

        while (startDate.Month != 8)
            startDate = startDate.AddMonths(-1);

        for (Int32 monthCount = 1; monthCount <=10; monthCount++)
        {
            ListItem newItem = new ListItem(startDate.ToString("MMMM") + " " + startDate.Year.ToString(), new DateTime(startDate.Year, startDate.Month, 1).ToShortDateString());
            MonthDropDown.Items.Add(newItem);
            startDate = startDate.AddMonths(1);
        }
        MonthDropDown.SelectedValue = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).ToShortDateString();
    }

    protected void monthDropDown_SelectedIndexChanged(object sender, EventArgs e)
    {
        RefreshMatchList();
    }

    protected void MatchRepeater_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        
        HiddenField espnMatchIdHidden = (HiddenField)e.Item.FindControl("EspnMatchIdHidden");
        Int32 espnMatchId = Convert.ToInt32(espnMatchIdHidden.Value);
        HiddenField matchDateHidden = (HiddenField)e.Item.FindControl("MatchDateHidden");
        DateTime matchDate = Convert.ToDateTime(matchDateHidden.Value);

        EspnImport espn = new EspnImport();
        
        ImportedMatch thisMatch = espn.GetMatchByEspnMatchId(espnMatchId, Convert.ToInt32(CompetitionDropDown.SelectedValue), matchDate);
        MatchDateLabel.Text = matchDate.ToShortDateString();
        HomeClubIdHidden.Value = thisMatch.HomeClubId.ToString();
        HomeClubGoalsHidden.Value = thisMatch.HomeGoals.ToString();
        AwayClubIdHidden.Value = thisMatch.AwayClubId.ToString();
        AwayClubGoalsHidden.Value = thisMatch.AwayGoals.ToString();
        MatchScoreLabel.Text = thisMatch.HomeClub + " " + thisMatch.HomeGoals + " " + thisMatch.AwayClub + " " + thisMatch.AwayGoals;
        PlayerListPanel.Visible = true;
        MatchListPanel.Visible = false;
        GetMatchesButton.Visible = false;
        PlayerListRepeater.DataSource = thisMatch.PlayerList;
        PlayerListRepeater.DataBind();
    }

    protected void UpdateButton_Click(object sender, EventArgs e)
    {
        DateTime matchDate = Convert.ToDateTime(MatchDateLabel.Text);
        Int32 competitionId = Convert.ToInt32(CompetitionDropDown.SelectedValue);
        Int32 homeClubId = Convert.ToInt32(HomeClubIdHidden.Value);
        Int32 homeClubGoals = Convert.ToInt32(HomeClubGoalsHidden.Value);
        Int32 awayClubId = Convert.ToInt32(AwayClubIdHidden.Value);
        Int32 awayClubGoals = Convert.ToInt32(AwayClubGoalsHidden.Value);

        Match matchInstance = new Match();
        matchInstance.Where.MatchDate.Value = matchDate;
        matchInstance.Where.HomeClubId.Value = homeClubId;
        matchInstance.Where.AwayClubId.Value = awayClubId;

        if (!matchInstance.Query.Load())
            matchInstance.AddNew();
        
        matchInstance.MatchDate = matchDate;
        matchInstance.CompetitionId = competitionId;
        if (homeClubId !=-1)
            matchInstance.HomeClubId = homeClubId;
        if(awayClubId!=-1)
            matchInstance.AwayClubId = awayClubId;
        matchInstance.HomeClubGoals = homeClubGoals;
        matchInstance.AwayClubGoals = awayClubGoals;
        matchInstance.Save();

        foreach (RepeaterItem playerScoreItem in PlayerListRepeater.Items)
        {
            Int32 playerId = Convert.ToInt32(((HiddenField)playerScoreItem.FindControl("PlayerIdHidden")).Value);
            Player thisPlayer = new Player();

            Int32 positionId = thisPlayer.LoadByPrimaryKey(playerId) ? thisPlayer.PositionId : 0;

            Boolean started = ((CheckBox)playerScoreItem.FindControl("StartedCheckBox")).Checked;
            Boolean playedAsSub = ((CheckBox)playerScoreItem.FindControl("PlayedAsSubCheckBox")).Checked;
            Int32 goals = Convert.ToInt32(((TextBox)playerScoreItem.FindControl("GoalsTextBox")).Text);
            Int32 bonusGoals = goals - 1;
            Boolean cleanSheet = ((CheckBox)playerScoreItem.FindControl("CleanSheetCheckBox")).Checked;
            Boolean concededOne = ((CheckBox)playerScoreItem.FindControl("ConcededOneCheckBox")).Checked;
            Boolean teamScoredThreePlus = ((CheckBox)playerScoreItem.FindControl("TeamScoredThreePlusCheckBox")).Checked;

            if (started)
                InsertUpdatePlayerScore(matchInstance.Id, playerId,positionId, 1, 1, 0);

            if (playedAsSub)
                InsertUpdatePlayerScore(matchInstance.Id, playerId, positionId, 2, 1, 0);

            if (cleanSheet && positionId <= 3)
                InsertUpdatePlayerScore(matchInstance.Id, playerId, positionId, 3, 1, 0);

            if (concededOne && positionId <=2)
                InsertUpdatePlayerScore(matchInstance.Id, playerId, positionId, 4, 1, 0);

            if (goals > 0)
                InsertUpdatePlayerScore(matchInstance.Id, playerId, positionId, 5, goals, bonusGoals);

            if (teamScoredThreePlus && positionId >=3)
                InsertUpdatePlayerScore(matchInstance.Id, playerId, positionId, 6, 1, 0);
        }
        
        PlayerListPanel.Visible = false;
        MatchListPanel.Visible = false;
        GetMatchesButton.Visible = true;

    }

    private void InsertUpdatePlayerScore(Int32 matchId, Int32 playerId, Int32 positionId, Int32 scoreType, Int32 amount, Int32 bonus)
    {
        Score thisScore = new Score();
        thisScore.Where.PositionId.Value = positionId;
        thisScore.Where.ScoreType.Value = scoreType;
        if (thisScore.Query.Load())
        {
            PlayerScore thisPlayerScore = new PlayerScore();
            thisPlayerScore.Where.MatchId.Value = matchId;
            thisPlayerScore.Where.PlayerId.Value = playerId;
            thisPlayerScore.Where.ScoreId.Value = thisScore.Id;
            if (!thisPlayerScore.Query.Load())
                thisPlayerScore.AddNew();

            thisPlayerScore.MatchId = matchId;
            thisPlayerScore.PlayerId = playerId;
            thisPlayerScore.ScoreId = thisScore.Id;
            thisPlayerScore.Amount = amount;
            thisPlayerScore.Bonus = bonus;
            thisPlayerScore.Save();
        }
    }

    protected Int32 GetPlayerId(Int32 espnPlayerId)
    {
        Int32 returnValue = 0;
        EspnPlayer thisEspn = new EspnPlayer();
        thisEspn.Where.EspnPlayerId.Value = espnPlayerId;
        if (thisEspn.Query.Load())
            returnValue = thisEspn.PlayerId;

        return returnValue;
    }

    protected String GetPlayerName(Int32 playerId)
    {
        String returnValue = String.Empty;
        Player thisPlayer = new Player();
        if (thisPlayer.LoadByPrimaryKey(playerId))
            returnValue = (thisPlayer.Forename + " " + thisPlayer.Surname).Trim();
        
        return returnValue;
    }

    protected String GetClubName(Int32 ClubId)
    {
        String returnValue = String.Empty;
        Club thisClub = new Club();
        if (thisClub.LoadByPrimaryKey(ClubId))
            returnValue = thisClub.ClubName;

        return returnValue;
    }

    protected void MatchRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            //Is match already in database?
            DateTime matchDate = Convert.ToDateTime(((HiddenField)e.Item.FindControl("MatchDateHidden")).Value);
            Int32 homeClubId = Convert.ToInt32(((HiddenField)e.Item.FindControl("HomeClubIdHidden")).Value);
            Int32 awayClubId = Convert.ToInt32(((HiddenField)e.Item.FindControl("AwayClubIdHidden")).Value);

            Match thisMatch = new Match();
            thisMatch.Where.MatchDate.Value = matchDate;
            if(homeClubId!=-1)
                thisMatch.Where.HomeClubId.Value = homeClubId;
            if(awayClubId!=-1)
                thisMatch.Where.AwayClubId.Value = awayClubId;
            if (thisMatch.Query.Load())
            {
                ((Button)e.Item.FindControl("AddButton")).Enabled = false;
                ((Button)e.Item.FindControl("EditButton")).Enabled = true;
            }
            else
            {
                ((Button)e.Item.FindControl("AddButton")).Enabled = true;
                ((Button)e.Item.FindControl("EditButton")).Enabled = false;
            }

        }
    }
    protected void GetMatchesButton_Click(object sender, EventArgs e)
    {
        RefreshMatchList();
        MatchListPanel.Visible = true;
    }
}
